package main.h2;

import org.h2.tools.Server;

import java.sql.*;

/**
 * Created by zhtt on 2016/10/17.
 */
public class H2Demo02 {
    private Server server;
    private String port = "8082";
    private String dbDir="~/test";
    private String user = "sa";
    private String password = "";

    public void startServer() {
        try {
            System.out.println("正在启动h2...");
            server = Server.createTcpServer(new String[] { "-tcpPort", port }).start();
        } catch (SQLException e) {
            System.out.println("启动h2出错：" + e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void stopServer() {
        if (server != null) {
            System.out.println("正在关闭h2...");
            server.stop();
            System.out.println("关闭成功.");
        }
    }

    public void useH2() {
        Connection conn=null;
        Statement stmt=null;
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:" + dbDir,
                    user, password);
            stmt = conn.createStatement();
            // insert data
            //stat.execute("CREATE TABLE TEST(NAME VARCHAR)");
            //stat.execute("INSERT INTO TEST VALUES('Hello World')");

            // use data
            ResultSet result = stmt.executeQuery("select name from test ");
            int i = 1;
            while (result.next()) {
                System.out.println(i++ + "---------->:" + result.getString("name"));
            }
            result.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(conn!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static void main(String[] args) {
        H2Demo02 h2 = new H2Demo02();
        h2.startServer();
        h2.useH2();
        h2.stopServer();
        System.out.println("==END==");
    }
}
